package com.nenglai.admin.modular.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nenglai.admin.handler.RequestHolder;
import com.nenglai.admin.modular.system.enums.AdminStatus;
import com.nenglai.admin.modular.system.enums.AdminType;
import com.nenglai.admin.modular.system.form.LoginForm;
import com.nenglai.admin.modular.system.form.RegisterForm;
import com.nenglai.admin.modular.system.form.ResetPasswordForm;
import com.nenglai.admin.modular.system.service.ReportAdminService;
import com.nenglai.admin.modular.system.util.AdminUtil;
import com.nenglai.admin.modular.system.vo.AdminVO;
import com.nenglai.common.crud.EditorBody;
import com.nenglai.common.crud.FormBody;
import com.nenglai.common.crud.RemoveBody;
import com.nenglai.common.crud.SearchBody;
import com.nenglai.common.enums.EnumUtils;
import com.nenglai.common.resource.Datalist;
import com.nenglai.common.resource.ResourceService;
import com.nenglai.common.response.ErrorCode;
import com.nenglai.common.response.ResponseException;
import com.nenglai.common.response.ValidateException;
import com.nenglai.common.vo.SearchOneVO;
import com.nenglai.common.vo.SearchVO;
import com.nenglai.model.system.entity.Admin;
import com.nenglai.model.system.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author kongdehui
 * @date 2021/06/13 11:17
 **/
@Slf4j
@Service
public class ReportAdminServiceImpl implements ReportAdminService, ResourceService<AdminVO> {

    @Resource
    IAdminService adminService;

    /**
     * 注册管理员
     *
     * @param form
     * @return boolean
     * @author kongdehui
     * @date 2021/04/21 13:42
     */
    @Override
    public boolean register(RegisterForm form) {
        String salt = AdminUtil.generateSalt().toString();
        Admin admin = new Admin();
        admin.setUsername(form.getUsername());
        admin.setPhone(form.getPhone());
        admin.setSalt(salt);
        admin.setAvatar(AdminUtil.generateAvatar());
        admin.setPassword(AdminUtil.generatePassword(form.getPassword(), salt));
        return adminService.save(admin);
    }

    @Override
    public boolean resetPassword(ResetPasswordForm form) {
        Admin admin = adminService.getById(form.getId());
        if (admin == null) {
            return false;
        }
        admin.setSalt(AdminUtil.generateSalt().toString());
        String password = AdminUtil.generatePassword(form.getPassword(), admin.getSalt());
        admin.setPassword(password);
        return adminService.saveOrUpdate(admin);
    }

    /**
     * 登录系统
     *
     * @param form
     * @return
     */
    @Override
    public Admin login(LoginForm form) {
        Admin admin = adminService.getOne(new QueryWrapper<Admin>().eq("username", form.getUsername()));
        if (admin != null) {
            String password = AdminUtil.generatePassword(form.getPassword(), admin.getSalt());
            if (password.equals(admin.getPassword())) {
                log.info("用户[{}]，登录成功！", admin.getUsername());
                return admin;
            }
        }
        return null;
    }

    @Override
    public Admin findOne(Long id) {
        return adminService.getById(id);
    }

    @Override
    public String resourceName() {
        return "admin";
    }

    @Override
    @Datalist(entity = Admin.class, vo = AdminVO.class)
    public SearchVO<Admin> search(SearchBody body) {
        QueryWrapper<Admin> query = body.query(new QueryWrapper<>(), Admin.class);
        Page<Admin> page = adminService.page(new Page<>(body.getPage(), body.getPagesize()), query);
        return new SearchVO<>(page.getRecords(), page.getTotal());
    }

    @Override
    public SearchOneVO<AdminVO> searchOne(SearchBody body) {
        Long id = body.getDataValue("id", Long.class);
        Admin admin = adminService.getById(id);
        SearchOneVO<AdminVO> VO = new SearchOneVO<>();
        if (admin != null) {
            VO.setInfo(
                    AdminVO.builder().id(admin.getId()).phone(admin.getPhone()).username(admin.getUsername()).build());
        }
        return VO;
    }

    @Override
    public Boolean delete(RemoveBody body) {
        QueryWrapper<Admin> query = body.query(new QueryWrapper<>(), Admin.class, true);
        Admin user = adminService.getOne(query);
        if (user == null) {
            throw new ResponseException(ErrorCode.OBJECT_DOES_NOT_EXIST);
        }

        Admin admin = (Admin) RequestHolder.getRequest().getAttribute("user");
        if (user.getId().equals(admin.getId())) {
            log.info("用户{}试图删除自己被禁止！", user.getId());
            throw new ResponseException(ErrorCode.PROHIBIT_ADMIN_REMOVE_SELF);
        }

        if (user.getType().equals(AdminType.TYPE_SUPER.getCode())) {
            throw new ResponseException(ErrorCode.PROHIBIT_REMOVE_SUPER);
        }

        return adminService.remove(query);
    }

    @Override
    public Object add(FormBody body) throws ValidateException {
        return null;
    }

    @Override
    public Object update(FormBody body) throws ValidateException {
        return null;
    }

    @Override
    public Boolean edit(EditorBody body) throws ValidateException {
        UpdateWrapper<Admin> update = body.query(new UpdateWrapper<>(), Admin.class, true);
        return adminService.update(update);
    }

    @Override
    public Object configs() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", EnumUtils.EnumToMapInt(AdminStatus.class));
        hashMap.put("type", EnumUtils.EnumToMapInt(AdminType.class));
        return hashMap;
    }
}
